package com.fyzk.activity.user;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.bean.ForgotPwdResponse1;
import com.fyzk.bean.ForgotPwdResponse2;
import com.fyzk.bean.ForgotPwdResponse3;
import com.fyzk.bean.ForgotPwdResponse4;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Pattern;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * 忘记密码
 *
 * @author fanxs11
 */
public class ForgotPwdActivity extends BaseActivity implements onTopTitleClickListener {

    private TopTitleView topView;

    private EditText userName_et;
    private EditText phone_et;
    private EditText yanZhengMa_et;
    private TextView chongFa_tv;
    private EditText newPwd_et;
    //	private EditText newPwd_et2;
    private Button btn;

    private LinearLayout userName_ll;
    private LinearLayout phone_ll;
    private LinearLayout yanZhengMa_ll;
    private LinearLayout newPwd_ll;

    private int type = 1;

//	private static final int DAOJISHI = 180;
//	public static int daojs_yzm = DAOJISHI;

    private final int DAOJISHI = 60;
    public int daojs_yzm = DAOJISHI;
    private Handler handler_yzm;
    private Runnable runnable_yzm;
    boolean hasSended = false;
    private EditText again;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgotpwd);

        initView();

        handler_yzm = new Handler();

        runnable_yzm = new Runnable() {

            @Override
            public void run() {
                djs_yzm();
            }
        };
    }

    private void initView() {
        //根据路径得到Typeface
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/pingfang.ttf");
        topView = (TopTitleView) findViewById(R.id.forgotpwd_topview);
        topView.setCenterText("找回密码");
        topView.setRightVisible(View.INVISIBLE);
        topView.setOnTitleClickListener(this);

        userName_et = (EditText) findViewById(R.id.forgotpwd_username_et);
        userName_et.setTypeface(tf);
        phone_et = (EditText) findViewById(R.id.forgotpwd_phoneno_et);
        phone_et.setTypeface(tf);
        yanZhengMa_et = (EditText) findViewById(R.id.forgotpwd_yanzhengma_et);
        yanZhengMa_et.setTypeface(tf);
        chongFa_tv = (TextView) findViewById(R.id.forgotpwd_yzm_chongfa);
        chongFa_tv.setTypeface(tf);
        newPwd_et = (EditText) findViewById(R.id.forgotpwd_newpwd_et);
        newPwd_et.setTypeface(tf);
        again = (EditText) findViewById(R.id.forgotpwd_again);
        again.setTypeface(tf);
//		newPwd_et2 = (EditText) findViewById(R.id.forgotpwd_newpwd_et2);
        btn = (Button) findViewById(R.id.forgotpwd_btn);
        btn.setTypeface(tf);
        userName_ll = (LinearLayout) findViewById(R.id.forgotpwd_username_ll);
        phone_ll = (LinearLayout) findViewById(R.id.forgotpwd_phone_ll);
        yanZhengMa_ll = (LinearLayout) findViewById(R.id.forgotpwd_yanzhengma_ll);
        newPwd_ll = (LinearLayout) findViewById(R.id.forgotpwd_newpwd_ll);

        if (daojs_yzm == 0 || daojs_yzm == DAOJISHI) {
            chongFa_tv.setClickable(true);
//			chongFa_tv.setTextColor(Color.BLUE);
            if (!hasSended) {
                chongFa_tv.setText(R.string.zhuce_center_fa);
            } else {
                chongFa_tv.setText(R.string.zhuce_center_chongfa);
            }
            daojs_yzm = DAOJISHI;
        } else {
            hasSended = true;
//			chongFa_tv.setTextColor(Color.GRAY);
            chongFa_tv.setClickable(false);
            chongFa_tv.setText(daojs_yzm + "秒后可重发");
        }

        chongFa_tv.setOnClickListener(this);
        btn.setOnClickListener(this);
        setVisibility(type);
    }

    //==============================================================================================
    private ForgotPwdResponse1 responseData1;
    private ForgotPwdResponse2 responseData2;
    private ForgotPwdResponse3 responseData3;
    private ForgotPwdResponse4 responseData4;
//	@Override
//	protected void request(int schemaDef) {
//		// TODO Auto-generated method stub
//		switch (schemaDef) {
//		case SchemaDef.FORGOTPWD_1:
//			forgotPwdRequest1(schemaDef);
//			break;
//		case SchemaDef.FORGOTPWD_2:
//			forgotPwdRequest2(schemaDef);
//			break;
//		case SchemaDef.FORGOTPWD_3:
//			forgotPwdRequest3(schemaDef);
//			break;
//		case SchemaDef.FORGOTPWD_4:
//			forgotPwdRequest4(schemaDef);
//			break;
//		default:
//			break;
//		}
//	}

//	String tips = "" ;
//	@Override
//	public void onProtocalSuccess(Object paramObject) {
//		// TODO Auto-generated method stub
//		if (paramObject instanceof ForgotPwdResponseData) {
//			responseData1 = (ForgotPwdResponseData) paramObject;
//			CommonResult result = responseData1.commonResult;
//			if (result.codeValue == 0) {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD1_SUCCESS);
//			} else {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD1_FAIL);
//			}
//		}else if (paramObject instanceof ForgotPwd2ResponseData) {
//			responseData2 = (ForgotPwd2ResponseData) paramObject;
//			CommonResult result = responseData2.commonResult;
//			if (result.codeValue == 0) {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD2_SUCCESS);
//			} else {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD2_FAIL);
//			}
//		}else if (paramObject instanceof ForgotPwd3ResponseData) {
//			responseData3 = (ForgotPwd3ResponseData) paramObject;
//			CommonResult result = responseData3.commonResult;
//			if (result.codeValue == 0) {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD3_SUCCESS);
//			} else {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD3_FAIL);
//			}
//		}else if (paramObject instanceof ForgotPwd4ResponseData) {
//			responseData4 = (ForgotPwd4ResponseData) paramObject;
//			CommonResult result = responseData4.commonResult;
//			if (result.codeValue == 0) {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD4_SUCCESS);
//			} else {
//				mHandler.sendEmptyMessage(HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD4_FAIL);
//			}
//		}
//	}
//
//	@Override
//	protected void parserMessage(Message msg) {
//		// TODO Auto-generated method stub
//		super.parserMessage(msg);
//		DJ_ProgressDialog.dissmiss();
//
//		switch (msg.what) {
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD1_SUCCESS:
//			type = 2;
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD1_FAIL:
//			if (responseData1 != null) {
//				AppToast.getToast().show(""+responseData1.commonResult.tips);
//			}
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD2_SUCCESS:
//			type = 3;
//			sendYZM();
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD2_FAIL:
//			if (responseData2 != null) {
//				AppToast.getToast().show(""+responseData2.commonResult.tips);
//			}
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD3_SUCCESS:
//			type = 4;
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD3_FAIL:
//			if (responseData3 != null) {
//				AppToast.getToast().show(""+responseData3.commonResult.tips);
//			}
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD4_SUCCESS:
//			AppToast.getToast().show("密码已成功找回，请重新登录");
//			finish();
//			break;
//		case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_FORGOTPWD4_FAIL:
//			if (responseData4 != null) {
//				AppToast.getToast().show(""+responseData4.commonResult.tips);
//			}
//			break;
//		default:
//			AppToast.getToast().show("网络异常");
//			break;
//		}
//		setVisibility(type);
//	}

//	/**
//	 * 忘记密码第一步
//	 */
//	private void request_forgotPwdRequest1(){
//
//		try {
//			JSONObject request_json = new JSONObject();
//			request_json.put("username", userName_et.getText().toString());
//			httpPostJson(CommandUtil.FORGOTPWD_1, Commands.FORGOTPWD_1, request_json, true);
//		} catch (JSONException e) {
//
//		}
//	}

    /**
     * 忘记密码第二步（获取验证码）
     */
    private void request_forgotPwdRequest2() {
        try {
            JSONObject request_json = new JSONObject();
//			request_json.put("username", userName_et.getText().toString());
            request_json.put("phone", phone_et.getText().toString());
            httpPostJson(CommandUtil.FORGOTPWD_2, Commands.FORGOTPWD_2, request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     * 忘记密码第三步（验证 验证码）
     */
    private void request_forgotPwdRequest3() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("phone", phone_et.getText().toString());
            request_json.put("validateCode", yanZhengMa_et.getText().toString());
            httpPostJson(CommandUtil.FORGOTPWD_3, Commands.FORGOTPWD_3, request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     * 忘记密码第四步（修改密码）
     */
    private void request_forgotPwdRequest4() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("userno", responseData2.getUserno());
            request_json.put("password", newPwd_et.getText().toString());
            httpPostJson(CommandUtil.FORGOTPWD_4, Commands.FORGOTPWD_4, request_json, true);
        } catch (JSONException e) {

        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FORGOTPWD_1:
                type = 2;
                break;
            case CommandUtil.FORGOTPWD_2:
                responseData2 = JSON.parseObject(resultBean.getData(), ForgotPwdResponse2.class);
                type = 2;
                sendYZM();
                break;
            case CommandUtil.FORGOTPWD_3:
                type = 3;
                break;
            case CommandUtil.FORGOTPWD_4:
                AppToast.getToast().show("密码已成功找回，请重新登录");
                finish();
                break;
            default:
                break;
        }
        setVisibility(type);
    }

    //==============================================================================================

    /**
     * 启动验证码倒计时
     */
    private void sendYZM() {
        daojs_yzm = DAOJISHI - 1;
//		chongFa_tv.setTextColor(Color.GRAY);
        chongFa_tv.setClickable(false);
        chongFa_tv.setText(daojs_yzm + "秒\n后重发");
        handler_yzm.post(runnable_yzm);
    }

    /**
     * 验证码 有效倒计时
     */
    private void djs_yzm() {
        handler_yzm.postDelayed(runnable_yzm, 1000);
        if (daojs_yzm == 0 || daojs_yzm == DAOJISHI) {
            handler_yzm.removeCallbacks(runnable_yzm);
            chongFa_tv.setClickable(true);
//			chongFa_tv.setTextColor(Color.BLUE);
            if (!hasSended) {
                chongFa_tv.setText(R.string.zhuce_center_fa);
            } else {
                chongFa_tv.setText(R.string.zhuce_center_chongfa);
            }
            daojs_yzm = DAOJISHI;
        } else {
            hasSended = true;
//			chongFa_tv.setTextColor(Color.GRAY);
            chongFa_tv.setClickable(false);
            chongFa_tv.setText(daojs_yzm + "秒后可重发");
            daojs_yzm -= 1;
        }
    }

    /**
     * 设置显示第几步操作
     *
     * @param type
     */
    private void setVisibility(int type) {
        switch (type) {
//		case 1:
//			userName_ll.setVisibility(View.GONE);
//			phone_ll.setVisibility(View.VISIBLE);
//			yanZhengMa_ll.setVisibility(View.VISIBLE);
//			newPwd_ll.setVisibility(View.GONE);
//			again.setVisibility(View.GONE);
//			phone_et.requestFocus();
//			phone_et.setSelectAllOnFocus(true);
//			break;
//		case 1:
//			userName_ll.setVisibility(View.GONE);
//			phone_ll.setVisibility(View.VISIBLE);
//			yanZhengMa_ll.setVisibility(View.GONE);
//			newPwd_ll.setVisibility(View.GONE);
//			again.setVisibility(View.GONE);
//			phone_et.requestFocus();
//			phone_et.setSelectAllOnFocus(true);
//			break;
            case 1:
//			userName_ll.setVisibility(View.GONE);
//			phone_ll.setVisibility(View.VISIBLE);
//			phone_et.setEnabled(false);
//			yanZhengMa_ll.setVisibility(View.VISIBLE);
//			newPwd_ll.setVisibility(View.GONE);
//			yanZhengMa_et.requestFocus();
//			yanZhengMa_et.setSelectAllOnFocus(true);
                userName_ll.setVisibility(View.GONE);
                phone_ll.setVisibility(View.VISIBLE);
                yanZhengMa_ll.setVisibility(View.VISIBLE);
                newPwd_ll.setVisibility(View.GONE);
                again.setVisibility(View.GONE);
                phone_et.requestFocus();
                phone_et.setSelectAllOnFocus(true);
                break;
            case 3:
                userName_ll.setVisibility(View.GONE);
                phone_ll.setVisibility(View.GONE);
                yanZhengMa_ll.setVisibility(View.GONE);
                newPwd_ll.setVisibility(View.VISIBLE);
                again.setVisibility(View.VISIBLE);
                btn.setText(getString(R.string.forgotpwd_btn_sure));
                newPwd_et.requestFocus();
                newPwd_et.setSelectAllOnFocus(true);
                break;
            default:
                break;
        }
    }

    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null
                || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }

        return false;
    }

    /**
     * 输入框确认
     *
     * @return
     */
    private boolean yanZheng() {
        switch (type) {
//		case 1:
//			if (isNull(userName_et)) {
//				userName_et.setError("用户名不能为空！");
//				return false;
//			}
//			break;
//		case 2:
//			if (isNull(phone_et)) {
//				phone_et.setError("手机号不能为空！");
//				return false;
//			}
//			if (!Pattern.matches("\\+86\\s*\\d{11}|\\d{11}", phone_et.getText().toString())) {
//				phone_et.setError("手机号码格式不正确！");
//				return false;
//			}
////			if (!phone_et.getText().toString().equals(responseData1.getData().getPhoneno())) {
////				phone_et.setError("手机号码与登记号码不符！");
////				return false;
////			}
//			break;
            case 1:
            case 2:
                if (isNull(phone_et)) {
                    phone_et.setError("手机号不能为空！");
                    return false;
                }
                if (!Pattern.matches("\\+86\\s*\\d{11}|\\d{11}", phone_et.getText().toString())) {
                    phone_et.setError("手机号码格式不正确！");
                    return false;
                }
                if (isNull(yanZhengMa_et)) {
                    yanZhengMa_et.setError("验证码不能为空！");
                    return false;
                }
                break;
            case 3:
                if (isNull(newPwd_et)) {
                    newPwd_et.setError("密码不能为空！");
                    newPwd_et.requestFocus();
                    newPwd_et.setSelectAllOnFocus(true);
                    return false;
                }
                if (!Pattern.matches("[a-zA-Z0-9_]{6,15}$", newPwd_et.getText().toString())) {
                    newPwd_et.setError("密码由6~15位字母、数字组成！");
                    newPwd_et.requestFocus();
                    newPwd_et.setSelectAllOnFocus(true);
                    return false;
                }
                if (!newPwd_et.getText().toString().equals(again.getText().toString())) {
                    showToast("两次输入密码不一致,请重新输入");
                    return false;
                }
//			if (isNull(newPwd_et2)) {
//				newPwd_et2.setError("确认密码不能为空！");
//				newPwd_et2.requestFocus();
//				newPwd_et2.setSelectAllOnFocus(true);
//				return false;
//			}
//			if (!newPwd_et.getText().toString().equals(newPwd_et2.getText().toString())) {
//				newPwd_et.setError("两次密码输入不符！");
//				newPwd_et.requestFocus();
//				newPwd_et.setSelectAllOnFocus(true);
//				return false;
//			}
                break;
            default:
                break;
        }

        return true;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.forgotpwd_yzm_chongfa:
                request_forgotPwdRequest2();
//			sendYZM();
                break;
            case R.id.forgotpwd_btn:
                if (!yanZheng()) {
                    return;
                }
                switch (type) {
//			case 1:
//				request_forgotPwdRequest1();
//				break;
                    case 1:
                        request_forgotPwdRequest2();
                        break;
                    case 2:
                        request_forgotPwdRequest3();
                        break;
                    case 3:
                        request_forgotPwdRequest4();
                        break;
                    default:
                        break;
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onLeftClick() {
        // TODO Auto-generated method stub
        finish();
    }

    @Override
    public void onCenterClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRightClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub

    }

}
